import { createStore } from 'vuex'
import feedback from './modules/feedback'

export default createStore({
    modules: {
        feedback
    },
    state:{
        token: null,
        user: null,
        userType: null,
    },
    mutations:{
        saveToken(state,token){
            state.token = token;
        },
        clearToken(state){
            state.token = null;
        },
        saveUser(state,user){
            state.user = user;
        },
        clearUser(state){
            state.user = null;
        },
        setUserType(state, type) {
            state.userType = type;
        },
        setUser(state, userData) {
            state.user = userData;
        }
    },
    actions:{
        saveToken({commit},token){
            commit('saveToken',token);
            localStorage.setItem('token',token);
        },
        removeToken({commit}){
            commit('clearToken');
            localStorage.removeItem('token');
        },
        saveUser({commit},user){
            commit('saveUser',user);
            localStorage.setItem('user', JSON.stringify(user));
        },
        saveUserType({ commit }, type) {
            commit('setUserType', type);
            localStorage.setItem('userType', type);
        }
    },
    getters:{
        isAuthenticated(state){
            return !!state.token;
        },
        getUser(state){
            return state.user;
        },
        isAdmin(state){
            return state.userType === 'admin';
        },
    },
})